package com.xxh.cloud.provider.service.impl;

import com.xxh.cloud.common.config.ContentConfig;
import com.xxh.cloud.common.util.NumberUtil;
import com.xxh.cloud.common.util.StringUtil;
import com.xxh.cloud.common.vo.R;
import com.xxh.cloud.provider.config.RedisKeyConfig;
import com.xxh.cloud.provider.entry.SmsLog;
import com.xxh.cloud.provider.mapper.SmsLogMapper;
import com.xxh.cloud.provider.service.inft.SmsLogService;
import com.xxh.cloud.provider.until.AliSmsUtil;
import com.xxh.cloud.provider.until.RedissonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
public class SmsLogServiceImpl implements SmsLogService {
    @Autowired
    private SmsLogMapper logMapper;

    @Override
    public R sendSmsLogin(String phone) {
        //入参效验
        if (!StringUtil.isEmpty(phone)){
            //2、验证是否为手机号
            if (phone.matches("^1[3-9][0-9]{9}$")){
                String key =  RedisKeyConfig.LOGIN_CODE+phone;
                //3.生成随机数字
                int code = NumberUtil.createNum(6);

                //查询验证码是否存在
                if (RedissonUtil.checkKeys(key)){
                    //如果验证码有效期剩余时间超过一半，还是返回老的验证码，同时更新有效期。如果小于一半，生成新的验证码，设置有效期
                    if (RedissonUtil.ttl(key)>RedisKeyConfig.LOGIN_CODE_TIME/2){
                        code=Integer.parseInt(RedissonUtil.getStr(key).toString());
                        RedissonUtil.expire(key,RedisKeyConfig.LOGIN_CODE_TIME);
                    }
                }
                //4、发生短信
                if (AliSmsUtil.sendSms(new AliSmsUtil.PassTem(AliSmsUtil.LOGIN_CODE,phone,
                        AliSmsUtil.setCode(code)))){
                    //5、存储验证码到redis中，设置有效期10分钟
                    RedissonUtil.addStrTime(RedisKeyConfig.LOGIN_CODE+phone,code,RedisKeyConfig.LOGIN_CODE_TIME);
                    //6、记录数据库
                    logMapper.insert(new SmsLog(phone, ContentConfig.SMS_LOGIN_CODE,"发送登陆短信验证码",new Date()));
                    return R.ok();

                }else {
                    return R.fail("阿里云短信服务异常！！！");
                }
            }
        }

        return R.fail("非法请求");
    }

    @Override
    public R all() {
        return R.ok(logMapper.selectList(null));
    }
}
